package com.graduation.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.graduation.client.CmnClient;
import com.graduation.client.LogClient;
import com.graduation.client.StudentClint;
import com.graduation.common.exception.ManageException;
import com.graduation.model.entity.*;
import com.graduation.model.enu.WorkStatusEnum;
import com.graduation.model.vo.SchoolInfoVo;
import com.graduation.model.vo.StudentQueryVo;
import com.graduation.user.mapper.StudentMapper;
import com.graduation.user.service.StudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.user.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianwenle
 * @since 2022-11-16
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private CmnClient cmnClient;
    @Autowired
    private LogClient logClient;
    @Autowired
    private StudentClint studentClint;

    @Autowired
    private TeacherService teacherService;

    @Override
    public Student getStudentById(Long id) {
        Student student = baseMapper.selectById(id);
        this.packageStudent(student);
        return student;
    }

    @Override
    public List<Student> getListInfo() {
        List<Student> students = baseMapper.selectList(null);
        students.forEach(this::packageStudent);
        return students;
    }

    @Override
    public Map<String, Object> findPageList(Integer pageSize, Integer pageNum, StudentQueryVo studentQueryVo) {
        Page<Student> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Student> wrapper = new QueryWrapper<>();


        if (!StringUtils.isEmpty(studentQueryVo.getUsername())) {
            wrapper.like("username", studentQueryVo.getUsername());
        }
        if (studentQueryVo.getYear() != null) {
            wrapper.eq("year", studentQueryVo.getYear());
        }
        if (studentQueryVo.getClassNo() != null) {
            wrapper.eq("class_No", studentQueryVo.getClassNo());
        }
        if (studentQueryVo.getClassName() != null) {
            wrapper.eq("class_Name", studentQueryVo.getClassName());
        }

        if (studentQueryVo.getDepartmentId() != null) {
            wrapper.eq("department_id", studentQueryVo.getDepartmentId());
        }

        baseMapper.selectPage(page, wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        page.getRecords().forEach(this::packageStudent);
        map.put("list", page.getRecords());

        return map;
    }

    @Override
    public List<SchoolInfoVo> getTeacherStudentList(String loginNo) {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", loginNo);
        Teacher teacher = teacherService.getOne(wrapper);

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacher.getId());
        List<Student> students = baseMapper.selectList(queryWrapper);
        ArrayList<SchoolInfoVo> schoolInfoVos = new ArrayList<>();
        for (Student student : students) {
            SchoolInfoVo schoolInfoVo = new SchoolInfoVo();
            schoolInfoVo.setLabel(student.getUsername());
            schoolInfoVo.setValue(student.getId().toString());
            schoolInfoVos.add(schoolInfoVo);
        }
        return schoolInfoVos;
    }

    @Override
    public Map<String, Object> pageMyStudent(Integer pageNum, Integer pageSize, StudentQueryVo studentQueryVo, String loginNo) {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", loginNo);
        Teacher teacher = teacherService.getOne(wrapper);

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacher.getId());
        if (!StringUtils.isEmpty(studentQueryVo.getUsername())) {
            queryWrapper.like("username", studentQueryVo.getUsername());
        }
        Page<Student> page = new Page<>(pageNum, pageSize);
        baseMapper.selectPage(page, queryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        page.getRecords().stream().forEach(this::packageStudent);
        map.put("list", page.getRecords());
        return map;
    }

    @Override
    public Student getStudentInfoDetail(String username) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", username);
        Student student = baseMapper.selectOne(wrapper);
        if (student == null) {
            throw new ManageException(20001, "身份信息异常！");
        }
        this.packageStudent(student);
        return student;
    }

    @Override
    public List<SchoolInfoVo> getPackageStudentInfo() {
        List<Student> students = baseMapper.selectList(null);
        ArrayList<SchoolInfoVo> schoolInfoVos = new ArrayList<>();
        for (Student student : students) {
            SchoolInfoVo schoolInfoVo = new SchoolInfoVo();
            schoolInfoVo.setLabel(student.getUsername());
            schoolInfoVo.setValue(student.getId().toString());
            schoolInfoVos.add(schoolInfoVo);
        }
        return schoolInfoVos;
    }

    @Override
    public void saveAndReload(Student student) {
        Map<String, String> stringInfo = student.getStringInfo();

//        // 循环查询数值后 将所有的文字转换为数值
//        for (Map.Entry<String, String> entry : stringInfo.entrySet()) {
//            try{
//                entry.setValue(Integer.parseInt(entry.getValue()) + "");
//            }catch (Exception e){
//                System.out.println("未修改");
//            }
//        }
        // 将数值进行判断覆盖原数据
        // 发现了很有意思的bug 选择提交的数据为数字 未修改的为字母
        String classname = stringInfo.get("classname");
        String teacherNo = stringInfo.get("teacherName");
        String classno = stringInfo.get("classno");
        String dept = stringInfo.get("dept");
        String year = stringInfo.get("year");


        if (judgeIsNumber(classname)) {
            student.setClassName(Long.parseLong(classname));
        }
        if (judgeIsNumber(teacherNo)) {
            student.setTeacherId(Long.parseLong(teacherNo));
        }
        if (judgeIsNumber(classno)) {
            student.setClassNo(Long.parseLong(classno));
        }
        if (judgeIsNumber(dept)) {
            student.setDepartmentId(Long.parseLong(dept));
        }
        if (judgeIsNumber(year)) {
            student.setYear(Long.parseLong(year));
        }

        packageStudent(student);


        baseMapper.updateById(student);


    }

    @Override
    public void addAndChangeInfo(Student student) {

        Map<String, String> stringInfo = student.getStringInfo();

        String classname = stringInfo.get("classname");
        String teacherNo = stringInfo.get("teacherName");
        String classno = stringInfo.get("classno");
        String dept = stringInfo.get("dept");
        String year = stringInfo.get("year");


        if (judgeIsNumber(classname)) {
            student.setClassName(Long.parseLong(classname));
        }
        if (judgeIsNumber(teacherNo)) {
            student.setTeacherId(Long.parseLong(teacherNo));
        }
        if (judgeIsNumber(classno)) {
            student.setClassNo(Long.parseLong(classno));
        }
        if (judgeIsNumber(dept)) {
            student.setDepartmentId(Long.parseLong(dept));
        }
        if (judgeIsNumber(year)) {
            student.setYear(Long.parseLong(year));
        }

        packageStudent(student);

        baseMapper.insert(student);
    }

    private boolean judgeIsNumber(String number) {

        try {
            if (Integer.parseInt(number) < 2147483639 && Integer.parseInt(number) > 0) {
                return true;
            }
        } catch (Exception ex) {
            return false;
        }


        return false;
    }


    private void packageStudent(Student student) {
        if (student.getYear() == null || student.getClassName() == null || student.getClassNo() == null || student.getYear() == 0 || student.getClassName() == 0 || student.getClassNo() == 0 || student.getDepartmentId() == null || student.getTeacherId() == null) {
            // 这里还不能直接进行返回 避免后续读取到这里读取不到信息，必须对stringInfo进行包装
            Map<String, String> map = new HashMap<>();
            // 如果省事 可以直接填充假的数据
            if (student.getYear() == null || student.getYear() == 0) {
                map.put("year", "");
            }
            if (student.getClassName() == null || student.getClassName() == 0) {
                map.put("classname", "");
            }
            if (student.getClassNo() == null || student.getClassNo() == 0) {
                map.put("classno", "");
            }
            if (student.getDepartmentId() == null || student.getDepartmentId() == 0) {
                map.put("dept", "");
            }
            if (student.getTeacherId() == null || student.getTeacherId() == 0) {
                // 添加指导老师的姓名
                map.put("teacherName", "");
            }
            // 存储数据
            student.setStringInfo(map);

            return;
        }
        Dict dictYear = cmnClient.getDictById(student.getYear());
        Dict className = cmnClient.getDictById(student.getClassName());
        Dict dictClasNo = cmnClient.getDictById(student.getClassNo());
        student.setFullInfo(dictYear.getName() + className.getName() + dictClasNo.getName());
        Dict dep = cmnClient.getDictById(student.getDepartmentId());
        student.setDepartmentName(dep.getName());

        Long teacherId = student.getTeacherId();
        String teacherName = studentClint.getTeacherNameById(teacherId);
        // 将字符串信息传入到执行存储的map集合中
        Map<String, String> map = new HashMap<>();
        map.put("year", dictYear.getName());
        map.put("classname", className.getName());
        map.put("classno", dictClasNo.getName());
        map.put("dept", dep.getName());
        // 添加指导老师的姓名
        map.put("teacherName", teacherName);
        // 存储数据
        student.setStringInfo(map);


        // 判断学生是否已经实习了
        Integer workStatus = student.getWorkStatus();
        student.setWorkStatusStr(WorkStatusEnum.getWorkStr(workStatus));


        // 判断当前用户是否上传了日志
        Long id = student.getId();

        InternshipLog log = null;

        try {
            log = logClient.getLogByStudentId(id);
        } catch (Exception ex) {
            log = null;
        }

        if (log == null) {
            student.setLog(false);
        } else {
            student.setLog(true);
            student.setInternshipLog(log);
            InternshipGrade grade = logClient.getGradeByLogId(log.getId());
            student.setInternshipGrade(grade);
        }


    }
}
